<template>
  <el-form
    ref="loginForm"
    :model="form"
    :rules="rules"
    label-width="0"
    size="large"
    @keyup.enter="login"
  >
    <el-form-item prop="user">
      <el-input
        v-model="form.username"
        :prefix-icon="User"
        clearable
        placeholder="请输入账号"
      >
      </el-input>
    </el-form-item>

    <el-form-item prop="password">
      <el-input
        v-model="form.password"
        :prefix-icon="Lock"
        clearable
        show-password
        placeholder="请输入密码"
      ></el-input>
    </el-form-item>

    <!--验证码-->
    <el-form-item>
      <div class="boxCode">
        <el-input
          v-model="form.captcha"
          :prefix-icon="CircleCheck"
          clearable
          placeholder="请输入验证码"
          class="plinpnt"
        ></el-input>
        <el-image :src="captcha.url" @click="getCodeApi" class="code"></el-image>
      </div>
    </el-form-item>

    <!-- 记住密码 -->
    <el-form-item style="margin-bottom: 10px">
      <el-col :span="12">
        <el-checkbox v-model="checkPassword" @change="onMemoPassword(checkPassword)" >记住密码</el-checkbox>
      </el-col>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" style="width: 100%" round @click="login">
        登录
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, reactive, onBeforeMount, } from "vue"
import { captchaImg, loginByJson } from '@api/login'
//aes
import { Encrypt,Decrypt } from "@utils/aes"
//hooks
import useLogin from "@hooks/useLogin"
import useMemoPassword from '@hooks/useMemoPassword'
//图标
import { User,Lock,CircleCheck } from '@element-plus/icons-vue'

//表单数据
const form = reactive({
    username:'',
    password:'',
    captcha:''
})

// 表单验证规则
const rules = reactive({

})

// 生命周期
onBeforeMount(()=>{
    // 获取验证码
    getCodeApi()

    // 记住密码
      // 获取到复选框的状态并重新赋值
        // 刚开始localstorag里没有状态，checkPassword为false
        // 当我点击的时候，checkPassword为true，并将状态存储到localstorage里
        // 刷新页面时，读取localstorage里的值（true）
    // （已封装为hoooks）checkPassword.value = localStorage.getItem('memoPassword') == 'true' ? true : false

      //获取到用户名和密码并重新赋值
    if(localStorage.getItem('user-pwd')){
      let {username,password} = JSON.parse(localStorage.getItem('user-pwd'))
      form.username = Decrypt(username)
      form.password = Decrypt(password)
    }
})

// 验证码图片
const captcha = reactive({
    url:'',
    key:''
})

// 生成验证码
const getCodeApi = async ()=>{
    const key = new Date().getTime().toString()
    captcha.key = key
    const res = await captchaImg({
        key,
    })
    let blob = new Blob([res], {type:'application/vnd.ms-excel'})
    let imgUrl = URL.createObjectURL(blob)
    captcha.url = imgUrl
} 

// hooks数据
let {memoVal,onMemoPassword} = useMemoPassword()

    /**
     * 1.首先从本地存储中读取复选框的状态（memoval）
     *   memoval刚开始为false，并在此处将值赋给checkPassword（是否打√）
     * 2.点击复选框的时候，更新状态，存储状态的变量是checkPassword为true。然后调用hooks里的onMemoPassword方法，将checkPassword传过去
     *  --onMemoPassword方法接收checkPassword的值，将memoval更新为该值，然后存进本地存储里
     * 3.刷新页面时，memova为true，checkPassword也为true
     */

// 记住密码-数据
let checkPassword = ref(memoVal)

// 记住密码
const setMemoPassword = ()=>{
  //（已封装为hooks） localStorage.setItem('memoPassword',checkPassword.value)
console.log(111,'记住密码');
  checkPassword.value ? localStorage.setItem('user-pwd',JSON.stringify({
    username:Encrypt(form.username),
    password:Encrypt(form.password)
  })) : localStorage.removeItem('user-pwd')
}

// 登录
const login = async ()=>{
    let res = await loginByJson({
        username:Encrypt(form.username),
        password:Encrypt(form.password),
        key:captcha.key,
        captcha:form.captcha
    })
    // console.log(res);
    if(res.code == '200'){
        // 调用hooks
          // hooks做了哪些事？
            /**
             * 1.存储token
             * 2.获取用户信息 ==>数据的存储和重构是在store里
             * 3.根据用户信息获取路由 ==>数据的存储和重构是在store里
             * 4.进入后台管理系统首页==>执行全局前置路由守卫
             */
        useLogin(res.data)//res.data就是token
        // 记住密码
        setMemoPassword()
    }
    
}
</script>

<style scoped>
.boxCode{
  display: flex;
  align-items: center;
  width: 100%;
}
.code{
  margin-left: 10px;
  height: 40px;
  cursor: pointer;
}
</style>
